package com.czk.zookeeper.curator.exsit;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/1/7 22:00
 */
public class CuratorExistDemo {
    String IP = "192.168.25.133:2181,192.168.25.133:2182,192.168.25.133:2183";
    CuratorFramework client;

    @Before
    public void before() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        client = CuratorFrameworkFactory.builder()
                .connectString(IP)
                .sessionTimeoutMs(50000)
                .retryPolicy(retryPolicy)
                .namespace("get")
                .build();
        client.start();
    }

    @After
    public void after() {
        client.close();
    }

    /**
     * 判断是否存在
     *
     * @throws Exception
     */
    @Test
    public void test1() throws Exception {
        Stat stat = client.checkExists()
                // 节点路径
                .forPath("");
        System.out.println(stat);
    }

    /**
     * 异步方式判断是否存在
     *
     * @throws Exception
     */
    @Test
    public void test2() throws Exception {
        client.checkExists()
                // 新开线程
                .inBackground(new BackgroundCallback() {
                    @Override
                    public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
                        System.out.println(curatorEvent.getPath());
                        System.out.println(curatorEvent.getType());
                        System.out.println(curatorEvent.getStat().getDataLength());
                    }
                })
                .forPath("");
        System.out.println("结束");
    }

    @Test
    public void test3() throws Exception {

    }

}
